package com.pfs.internal.timestamp.actions;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.pfs.internal.timestamp.entities.Leave;
import com.pfs.internal.timestamp.reports.LeavesReadExcel;
import com.pfs.internal.timestamp.utils.Constant;
import com.pfs.internal.timestamp.utils.ExcelUtil;

@SuppressWarnings("serial")
public class UploadAction extends ActionSupport {
	private File fileUpload;
	private String fileUploadContentType;
	private String fileUploadFileName;
	private String message;
	private String state;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Actions({ @Action(value = "ts-upload-myleaves", results = { @Result(name = "success", location = "/WEB-INF/content/echo.jsp") }) })
	public String upload() throws Exception {
		File fileToCreate = null;
		List<Leave> leaves = null;
		try {
			fileToCreate = new File(this.fileUploadFileName);
			FileUtils.copyFile(this.fileUpload, fileToCreate);
			if (!fileUpload.exists())
				throw new Exception(this.fileUploadFileName + " not found");
			Workbook wb = ExcelUtil.excel2Workbook(this.fileUpload);
			LeavesReadExcel readExcel = new LeavesReadExcel(wb);
			leaves = readExcel.readExcel();
			Collections.sort(leaves);
			updateId(leaves);
			Map session = ActionContext.getContext().getSession();
			session.put(UPLOAD_LEAVES, leaves);
		} catch (Exception e) {
			throw e;
		}
		setMessage("Cập nhật thành công ");
		setState(Constant.SUCCESS);
		return SUCCESS;
	}

	private void updateId(List<Leave> leaves) {
		int i = 0;
		for (Leave leave : leaves) {
			leave.setId(i);
			i++;
		}

	}

	public File getFileUpload() {
		return fileUpload;
	}

	public void setFileUpload(File fileUpload) {
		this.fileUpload = fileUpload;
	}

	public String getFileUploadContentType() {
		return fileUploadContentType;
	}

	public void setFileUploadContentType(String fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}

	public String getFileUploadFileName() {
		return fileUploadFileName;
	}

	public void setFileUploadFileName(String fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public static final String UPLOAD_LEAVES = "UPLOAD_LEAVES";
}
